﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReaderExtractTool.Service
{
    public class _477ZWService : BaseService
    {
        /// <summary>
        /// 提取文章内容
        /// </summary>
        /// <param name="chapterList"></param>
        /// <param name="unnecessaryContentStart"></param>
        /// <returns></returns>
        public override string GetChapterContent(Chapter chapter, string unnecessaryContentStart)
        {
            var doc = new HtmlWeb().Load(chapter.link);
            var node = doc.DocumentNode;
            var result = node.SelectNodes(".//div[@id='content']");
            string content = result[0].InnerHtml.Replace("<br>", "\r\n");

            if (!string.IsNullOrEmpty(unnecessaryContentStart))
            {
                int index = content.IndexOf(unnecessaryContentStart);
                content = content.Substring(0, index);
            }
            return chapter.name + "\r\n" + content + "\r\n\r\n";
        }

        /// <summary>
        /// 提取章节目录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="novelTitle"></param>
        /// <returns></returns>
        public override List<Chapter> GetChapters(string url, ref string novelTitle)
        {
            List<Chapter> chapterList = new List<Chapter>();

            var doc = new HtmlWeb().Load(url);
            var node = doc.DocumentNode;
            var result = node.SelectNodes(".//div[@id='list']/dl");
            if (result == null || result.Count == 0) throw new Exception("未检测到章节目录");

            // 提取所有章节目录
            foreach (var r in result)
            {
                if (string.IsNullOrEmpty(r.InnerHtml)) continue;

                var titleNode = r.ChildNodes.FirstOrDefault(f => f.Name == "dt");
                novelTitle = titleNode.InnerText.Replace("《", "").Replace("》", "").Replace(" ", "").Replace("正文", "");

                var chapterNodes = r.ChildNodes.Where(w => w.Name == "dd");
                if (chapterNodes == null || chapterNodes.Count() == 0) continue;
                foreach (var chapterNode in chapterNodes)
                {
                    string chapterName = chapterNode.InnerText;
                    string chapterLink = chapterNode.ChildNodes[0].Attributes["href"].Value;
                    chapterList.Add(new Chapter()
                    {
                        name = chapterName,
                        link = url + chapterLink.Split('/').LastOrDefault()
                    });
                }
            }

            return chapterList;
        }
    }
}
